//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.seeyon.ctp.common.web.filter;

import com.seeyon.ctp.cluster.ClusterConfigBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.LockLoginInfoFactory;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.config.SystemConfig;
import com.seeyon.ctp.common.constants.Constants;
import com.seeyon.ctp.common.constants.LoginResult;
import com.seeyon.ctp.common.constants.Constants.login_sign;
import com.seeyon.ctp.common.i18n.ResourceUtil;
import com.seeyon.ctp.common.po.restlog.CtpRestLogs;
import com.seeyon.ctp.common.restlog.manager.CtpRestLogsManager;
import com.seeyon.ctp.common.web.util.WebUtil;
import com.seeyon.ctp.login.CurrentUserToSeeyonApp;
import com.seeyon.ctp.login.LoginTokenUtil;
import com.seeyon.ctp.rest.util.RestUrlFilterUtil;
import com.seeyon.ctp.rest.vo.RestResourceGroupVO;
import com.seeyon.ctp.services.security.ServiceManager;
import com.seeyon.ctp.usersystem.manager.ResourceGroupManager;
import com.seeyon.ctp.usersystem.manager.RestUserManager;
import com.seeyon.ctp.usersystem.po.RestUser;
import com.seeyon.ctp.util.Cookies;
import com.seeyon.ctp.util.Strings;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

public class RestAuthenticator extends AbstractAuthenticator {
    private static final Logger log = Logger.getLogger(RestAuthenticator.class);
    protected RestUserManager restUserManager;
    protected ResourceGroupManager resourceGroupManager;
    private SystemConfig systemConfig = null;
    protected static Collection<Pattern> sessionUserBlacklist = new CopyOnWriteArrayList();
    private static List<String> anonymousWhiteList;
    private static List<String> guestWhiteList;
    private static List<String> visitorWhiteList;
    protected CtpRestLogsManager ctpRestLogsManager;

    public RestAuthenticator() {
    }

    public void setCtpRestLogsManager(CtpRestLogsManager ctpRestLogsManager) {
        this.ctpRestLogsManager = ctpRestLogsManager;
    }

    public CtpRestLogsManager getCtpRestLogsManager() {
        if (this.ctpRestLogsManager == null) {
            this.ctpRestLogsManager = (CtpRestLogsManager)AppContext.getBean("ctpRestLogsManager");
        }

        return this.ctpRestLogsManager;
    }

    public void setRestUserManager(RestUserManager restUserManager) {
        this.restUserManager = restUserManager;
    }

    public RestUserManager getRestUserManager() {
        if (this.restUserManager == null) {
            this.restUserManager = (RestUserManager)AppContext.getBean("restUserManager");
        }

        return this.restUserManager;
    }

    public void setResourceGroupManager(ResourceGroupManager resourceGroupManager) {
        this.resourceGroupManager = resourceGroupManager;
    }

    public ResourceGroupManager getResourceGroupManager() {
        if (this.resourceGroupManager == null) {
            this.resourceGroupManager = (ResourceGroupManager)AppContext.getBean("resourceGroupManager");
        }

        return this.resourceGroupManager;
    }

    protected boolean isIgnoreToken(String path) {
        Iterator var2 = anonymousWhiteList.iterator();

        String string;
        do {
            if (!var2.hasNext()) {
                return false;
            }

            string = (String)var2.next();
            if (string.equals(path)) {
                return true;
            }
        } while(!path.startsWith(string));

        return true;
    }

    public boolean authenticate(HttpServletRequest request, HttpServletResponse response) {
        String path = request.getRequestURI().substring(request.getContextPath().length() + "/rest/".length());
        this.initContext(request, response);
        String ip = Strings.getRemoteAddr(request);
        CtpRestLogs ctpLog = new CtpRestLogs();
        ctpLog.setExeurl(path);
        ctpLog.setLoginIp(ip);
        boolean ignoreToken = this.isIgnoreToken(path);
        if (!ignoreToken) {
            label205: {
                String token = getToken(request);
                if (!Strings.isEmpty(token) && !"null".equalsIgnoreCase(token)) {
                    ServiceManager.getInstance();
                    if (ServiceManager.checkToken(token)) {
                        ctpLog.setToken(token);
                        AppContext.putThreadContext("THREAD_CONTEXT_SESSION_KEY", request.getSession(true));
                        AppContext.putSessionContext(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, request.getLocale());
                        ServiceManager.getInstance().initCurrentUser(request, token);
                        User currentUser = AppContext.getCurrentUser();
                        if (currentUser != null) {
                            if (currentUser.isGuest()) {
                                if (!this.isGuestAccessable(path)) {
                                    this.unauthorized(request, "该资源不允许Guest访问：" + path);
                                    return true;
                                }
                            } else if (currentUser.isVisitor() && !this.isVisitorAccessable(path)) {
                                this.unauthorized(request, "该资源不允许Visitor访问：" + path);
                                return true;
                            }
                        }

                        String loginName = ServiceManager.getInstance().getUserNameByToken(token);

                        try {
                            RestUser user = this.getRestUserManager().getUserByLoginName(loginName);
                            if (user == null) {
                                if (!ServiceManager.CUSTOM_REST_USER_NAME.equals(loginName)) {
                                    boolean isClusterRequest = false;
                                    if (ClusterConfigBean.getInstance().isClusterEnabled()) {
                                        String remoteAddr = Strings.getRemoteAddr(request);
                                        if (ClusterConfigBean.getInstance().getHosts().indexOf(remoteAddr) > 0) {
                                            isClusterRequest = true;
                                        }
                                    }

                                    if (!isClusterRequest) {
                                        ctpLog.setStatus("0获取REST用户失败！");
                                        this.getCtpRestLogsManager().insertLog(ctpLog);
                                        this.unauthorized(request, "获取REST用户失败！");
                                        return true;
                                    }
                                }
                            } else {
                                ctpLog.setUserId(user.getId());
                                ctpLog.setLoginType("T");
                            }

                            List<RestResourceGroupVO> resourceGroupVOS = this.getResourceGroupManager().getRestResourceGroupVO();
                            Map<String, String> ruiTypeMap = this.getResourceUri(resourceGroupVOS);
                            String uriKey = this.uriVerification(path, ruiTypeMap);
                            String accountLockMode;
                            if (StringUtils.isNotBlank(uriKey)) {
                                accountLockMode = (String)ruiTypeMap.get(uriKey);
                                boolean falg = this.authorityVerification(user, accountLockMode);
                                if (user != null && ("wechat".equals(user.getUserName()) || "vjoin".equals(user.getUserName()) || "seeyons1".equals(user.getUserName()) || "seeyonbiinside".equals(user.getUserName()))) {
                                    falg = true;
                                }

                                if (!falg) {
                                    String message = " " + loginName + "无权限访问" + path + "需授权";
                                    this.unauthorized(request, "2248" + message);
                                    return true;
                                }
                            }

                            if (currentUser != null) {
                                accountLockMode = this.getSystemConfig().get("account_lock_mode");
                                if ("account".equals(accountLockMode)) {
                                    int USER_LOGIN_COUNT = Integer.parseInt(this.getSystemConfig().get("account_lock_times"));
                                    Constants.login_sign[] var16 = login_sign.values();
                                    int var17 = var16.length;

                                    for(int var18 = 0; var18 < var17; ++var18) {
                                        Constants.login_sign sign = var16[var18];
                                        LockLoginInfoFactory.LockLoginInfo info = LockLoginInfoFactory.getInstance().get(currentUser.getLoginName(), sign.value());
                                        info = LockLoginInfoFactory.getInstance().get(currentUser.getLoginName(), sign.value());
                                        if (("enable".equals(this.getSystemConfig().get("is_open_lock_protect")) || currentUser != null) && info != null && info.getCount() >= USER_LOGIN_COUNT) {
                                            this.unauthorized(request, "2248" + ResourceUtil.getString("loginUserState.accountLock"));
                                            return true;
                                        }
                                    }
                                }
                            }
                        } catch (Throwable var23) {
                            ctpLog.setStatus("0获取REST用户失败！");
                            log.error("获取REST用户失败！" + var23.getLocalizedMessage(), var23);
                        }

                        try {
                            ctpLog.setStatus(ctpLog.getStatus() == null ? "1" : ctpLog.getStatus());
                            break label205;
                        } catch (Exception var22) {
                            ctpLog.setStatus("0");
                            this.unauthorized(request, var22.getLocalizedMessage());
                            return true;
                        }
                    }
                }

                HttpSession session = request.getSession(false);
                boolean hasCurrentUser = session != null && session.getAttribute("com.seeyon.current_user") != null;
                String input;
                if (hasCurrentUser) {
                    User currentUser = AppContext.getCurrentUser();
                    if (currentUser == null) {
                        this.unauthorized(request, "Session没有对应的登录用户");
                        return true;
                    }

                    if (currentUser.isGuest()) {
                        if (!this.isGuestAccessable(path)) {
                            this.unauthorized(request, "该资源不允许Guest访问：" + path);
                            return true;
                        }
                    } else if (currentUser.isVisitor() && !this.isVisitorAccessable(path)) {
                        this.unauthorized(request, "该资源不允许Visitor访问：" + path);
                        return true;
                    }

                    input = CurrentUserToSeeyonApp.getUserOnlineMessage(request, true);
                    if (input != null) {
                        if (currentUser != null) {
                        }

                        this.unauthorized(request, input);
                        return true;
                    }

                    input = request.getMethod() + " " + path;
                    Iterator var12 = sessionUserBlacklist.iterator();

                    while(var12.hasNext()) {
                        Pattern p = (Pattern)var12.next();
                        if (p.matcher(input).find()) {
                            this.unauthorized(request, "请使用Token，Session登录不允许访问该接口：" + path);
                            return true;
                        }
                    }

                    AppContext.initSystemEnvironmentContext(request, response);

                    try {
                        String[] sessionMap = session.getAttribute("com.seeyon.current_user").toString().split("\t");
                        ctpLog.setUserId(Long.parseLong(sessionMap[0]));
                    } catch (Exception var21) {
                        this.unauthorized(request, "会话已失效。");
                        return true;
                    }

                    ctpLog.setToken(session.getId());
                    ctpLog.setLoginType("S");
                    ctpLog.setStatus("1");
                } else {
                    LoginResult loginResult = LoginTokenUtil.checkLoginToken(request);
                    if (!loginResult.isOK()) {
                        ctpLog.setToken("invalid");
                        ctpLog.setUserId(0L);
                        ctpLog.setLoginType("S");
                        ctpLog.setStatus("0");
                        input = loginResult.getStatus() == 1010 ? ResourceUtil.getString("loginUserState.unknown") : ResourceUtil.getString("login.label.ErrorCode." + loginResult.getStatus());
                        this.unauthorized(request, loginResult.getStatus() + ":" + input);
                        return true;
                    }

                    ctpLog.setToken(request.getHeader("ltoken"));
                    ctpLog.setLoginType("L");
                    ctpLog.setStatus("1");
                }
            }
        }

        if (!ignoreToken) {
            this.getCtpRestLogsManager().insertLog(ctpLog);
        }

        HttpSession session = request.getSession(false);
        if (session == null) {
            session = request.getSession(true);
            AppContext.putThreadContext("THREAD_CONTEXT_SESSION_KEY", session);
            AppContext.putSessionContext(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, request.getLocale());
        }

        this.updateAccessTimestamp();
        return true;
    }

    public boolean validate(String uri, HttpServletRequest req) {
        return uri.startsWith(req.getContextPath() + "/rest/");
    }

    private void initContext(HttpServletRequest request, HttpServletResponse response) {
        AppContext.clearThreadContext();
        AppContext.removeThreadContext("SESSION_CONTEXT_USERINFO_KEY");
        HttpSession session = request.getSession(false);
        if (session != null) {
            AppContext.putThreadContext("THREAD_CONTEXT_SESSION_KEY", session);
            AppContext.putSessionContext(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, request.getLocale());
        }

        AppContext.putThreadContext("THREAD_CONTEXT_REQUEST_KEY", request);
        WebUtil.setRequest(request);
        WebUtil.setResponse(response);
    }

    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (Strings.isEmpty(token)) {
            token = request.getParameter("token");
        }

        if (Strings.isEmpty(token)) {
            token = Cookies.get(request, "token");
        }

        return token;
    }

    private boolean isGuestAccessable(String path) {
        Iterator var2 = guestWhiteList.iterator();

        String string;
        do {
            if (!var2.hasNext()) {
                return false;
            }

            string = (String)var2.next();
        } while(!path.startsWith(string));

        return true;
    }

    private boolean isVisitorAccessable(String path) {
        Iterator var2 = visitorWhiteList.iterator();

        String string;
        do {
            if (!var2.hasNext()) {
                return false;
            }

            string = (String)var2.next();
        } while(!path.startsWith(string));

        return true;
    }

    void unauthorized(Object req, String message) {
        AppContext.putThreadContext("REST_UNAUTHORIZED_MESSAGE", message);
    }

    private boolean authorityVerification(RestUser user, String groupType) {
        boolean flag = false;
        if (StringUtils.isNotBlank(groupType) && user != null && user.getResourceAuthority() != null) {
            String[] resources = user.getResourceAuthority().split("");
            int groupTypeNum = Integer.valueOf(groupType);
            if (groupTypeNum <= resources.length && "1".equals(resources[groupTypeNum - 1])) {
                flag = true;
            }
        }

        return flag;
    }

    private String uriVerification(String path, Map<String, String> ruiTypeMap) {
        String uriKey = "";
        if (ruiTypeMap != null && ruiTypeMap.size() > 0) {
            Iterator var4 = ruiTypeMap.entrySet().iterator();

            while(var4.hasNext()) {
                Map.Entry<String, String> ruiType = (Map.Entry)var4.next();
                String pattern = (String)ruiType.getKey();
                boolean flag = RestUrlFilterUtil.checkUrl(path, pattern);
                if (flag) {
                    uriKey = pattern;
                    break;
                }
            }
        }

        return uriKey;
    }

    private Map<String, String> getResourceUri(List<RestResourceGroupVO> resourceGroupVOS) {
        Map<String, String> ruiTypeMap = new HashMap();
        if (resourceGroupVOS != null && resourceGroupVOS.size() > 0) {
            Iterator var3 = resourceGroupVOS.iterator();

            while(var3.hasNext()) {
                RestResourceGroupVO vo = (RestResourceGroupVO)var3.next();
                String resourceUrl = vo.getResourceUri();
                String[] uris = resourceUrl.split("/");
                StringBuffer uriBuffer = new StringBuffer();

                for(int i = 0; i < uris.length; ++i) {
                    String uri = uris[i];
                    if (uri != null && uri.trim().length() > 0) {
                        if (uri.indexOf("{") != -1) {
                            String str = uri.replaceAll("\\{[^}]*\\}", "(.*?)");
                            uriBuffer.append(str).append("/");
                        } else {
                            uriBuffer.append(uri + "/");
                        }
                    }
                }

                String uri = uriBuffer.substring(0, uriBuffer.length() - 1);
                ruiTypeMap.put(uri, vo.getGroupType());
            }
        }

        return ruiTypeMap;
    }

    public SystemConfig getSystemConfig() {
        if (this.systemConfig == null) {
            this.systemConfig = (SystemConfig)AppContext.getBean("systemConfig");
        }

        return this.systemConfig;
    }

    static {
        sessionUserBlacklist.add(Pattern.compile(".*\\sorgMember.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sorgAccount.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sorgDepartment.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sorgPost.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sorgLevel.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sexternalAccount.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sorgPartTimeJob.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sjoinOrgAccount.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sjoinOrgDepartment.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sjoinOrgPost.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sjoinOrgMember.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sjoinOrgRole.*"));
        sessionUserBlacklist.add(Pattern.compile(".*\\sjoinMetadataDepartment.*"));
        anonymousWhiteList = Arrays.asList("token", "application.wadl", "jssdk", "getRestCompare", "authentication", "cap4/form/pluginScripts", "orgMember/avatar", "orgMember/groupavatar", "m3/appManager/getAppList", "m3/appManager/download", "m3/message/unreadCount/", "m3/login/refresh", "m3/login/verification", "m3/theme/homeSkin", "m3/theme/homeSkinDownload", "m3/common/service/enabled", "uc/systemConfig", "product/hasPlugin", "product/dongle/data", "password/retrieve", "m3/appManager/checkEnv", "m3/security/device/apply", "meeting/meetingInviteCard", "microservice", "media/verify", "metrics", "ocip/forwardTo", "imc/orgInfo","myjsxy");
        guestWhiteList = Arrays.asList("webOffice/checkWebOfficeEnable", "webOffice/getBookMarkUpdateFlag", "webOfficeTrans/buildWebOfficeParams");
        visitorWhiteList = Arrays.asList("publicQrCode", "attachment", "commonImage", "m3/common/getConfigInfo", "meeting", "cmpNews", "doc");
    }
}
